layui.config({
    base: '/static/admin/treetable/module/'
}).extend({
    treetable: 'treetable-lay/treetable'
}).use(['layer','table', 'treetable', 'form'], function () {
    var $ = layui.jquery;
    var table = layui.table;
    var treetable = layui.treetable;
    var form = layui.form;
    
    //监听添加菜单的提交
    form.on('submit(formAdd)', function(data){
      addMenu(data.field);
      return false;
    });
    
    //监听修改菜单的提交
    form.on('submit(formUpdate)', function(data){
      updateMenu(data.field);
      return false;
    });
    
    
    // 渲染表格
    var renderTable = function () {
        layer.load(2);
        treetable.render({
            treeColIndex: 0,//树形图标显示在第几列
            treeSpid: -1,//最上级的父级id
            //checkbox: true,
            treeIdName: 'id',//id字段的名称
            treePidName: 'parentId',//pid字段的名称
            treeLinkage: false,//父级展开时是否自动展开所有子级
            elem: '#menu-table',
            url: '/admin/sys/menu/ajaxMenuList',
            page: false,
            cols: [[
                //{type: 'numbers', title: '↓'},
                {field: 'name', minWidth: 200, title: '菜单名称'},
                {field: 'path', title: '菜单路径'},
                {field: 'perm', title: '权限标识'},
                {field: 'parentId', title: '父级ID'},
                {field: 'type', title: '菜单类型', align:'center', width: 100, templet: function(d){
                	if(d.type == 0){
                		return '<span class="layui-badge layui-bg-orange">目录</span>';
                	}else if(d.type == 1){
                		return '<span class="layui-badge">菜单</span>';
                	}else if(d.type == 2){
                		return '<span class="layui-badge layui-bg-green">操作</span>';
                	}else {
                		return '';
                	}
                }},
                {field: 'icon', width: 100, align:'center', title: '菜单图标', templet: function(d){
                	return '<span title="'+d.icon+'"><i class="menu-icon fa '+d.icon+'"></i></span>';
                }},
                {field: 'sort', width: 80, align: 'center', title: '排序号'},
                /* {//暂时不用，后期需要可以添加
                    field: 'isMenu', width: 80, align: 'center', templet: function (d) {
                        if (d.isMenu == 1) {
                            return '<span class="layui-badge layui-bg-gray">按钮</span>';
                        }
                        //if (d.parentId == -1 || d.parentId == null || d.parentId == '') {
                    	if (d.perm == null) {
                            return '<span class="layui-badge layui-bg-blue">目录</span>';
                        } else {
                            return '<span class="layui-badge-rim">菜单</span>';
                        }
                    }, title: '类型'
                }, */
                {templet: '#auth-state', width: 180, align: 'center', title: '操作'}
            ]],
            done: function () {
                layer.closeAll('loading');
            }
        });
    };
    
    renderTable();

    $('#btn-expand').click(function () {
        treetable.expandAll('#menu-table');
    });

    $('#btn-fold').click(function () {
        treetable.foldAll('#menu-table');
    });

    $('#btn-refresh').click(function () {
        renderTable();
    });
    
    //监听工具条
    table.on('tool(menu-table)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'add') {
            confirmOperationMenu(data, '增加');
            
            //将菜单列表添加到下拉选中
            var menus = getAllMenus();
            for(var i = 0; i < menus.length; i++){
            	if(data.id == menus[i].id){//添加父级菜单下拉选,并设置被点击的选项为默认选中
                	$('#parentId').append('<option value="' + menus[i].id + '" selected>' + menus[i].name + '</option>');		                		
            	}else{
                	$('#parentId').append('<option value="' + menus[i].id + '">' + menus[i].name + '</option>');
            	}
            }
            form.render();//再次加载form，否则下拉选不显示
        } else if (layEvent === 'del') {
            layer.confirm(
            		'确定要删除菜单【'+data.name+'】及其子项吗？',
            		{icon: 3, title:'提示'},
            		function(index){
            			deleteMenu(data.id);
            			layer.close(index);
            		}
            	);
        } else if (layEvent === 'edit') {
            confirmOperationMenu(data, '修改');
            
            //将菜单列表添加到下拉选中
            var menus = getAllMenus();
            for(var i = 0; i < menus.length; i++){
            	if(data.parentId == menus[i].id){//添加父级菜单下拉选,并设置父级选项为默认选中
                	$('#parentId').append('<option value="' + menus[i].id + '" selected>' + menus[i].name + '</option>');		                		
            	}else{
                	$('#parentId').append('<option value="' + menus[i].id + '">' + menus[i].name + '</option>');
            	}
            }
            $('#typeId').find('option[value='+data.type+']').prop('selected','selected');//设置菜单类型默认选中
            form.render();//再次加载form，否则下拉选不显示
        }
    });
    
    $('#btn-search').click(function () {
        var keyword = $('#edt-search').val();
        var searchCount = 0;
        $('#auth-table').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
            $(this).css('background-color', 'transparent');
            var text = $(this).text();
            if (keyword != '' && text.indexOf(keyword) >= 0) {
                $(this).css('background-color', 'rgba(250,230,160,0.5)');
                if (searchCount == 0) {
                    treetable.expandAll('#auth-table');
                    $('html,body').stop(true);
                    $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                }
                searchCount++;
            }
        });
        if (keyword == '') {
            layer.msg("请输入搜索内容", {icon: 5});
        } else if (searchCount == 0) {
            layer.msg("没有匹配结果", {icon: 5});
        }
    });
});

//获取所有的菜单
function getAllMenus(){
	var menus = '';
	$.ajax({
		url:'/admin/sys/menu/ajaxMenuList',
		type: 'post',
		dataType: 'json',
		async: false,
		success: function(obj){
			if(obj.status == 200) {
				menus = obj.data;
			}
		},
		error: function(obj){
			gritterError(obj.msg);
		}
	});
	return menus;
}

var openIndex;//记录打开的弹窗的index值，方便添加、修改后关闭该弹窗
//layer弹出框
function confirmOperationMenu(data, title) {
	var form = layui.form;
	openIndex = layer.open({
        type: 1,
        title: title,
        closeBtn: 1,//0表示显示，1、2表示不同风格的关闭按钮
        shadeClose: true,
        content: operationDialog(data, title),
        success:function(index, layero){
	    	form.render();//重新加载，否则单选、复选、下拉选不显示
	    }
    });
}

//添加-修改菜单的弹窗
function operationDialog(data, title){
	if(title == '增加'){
		return '<form class="layui-form layui-form-pane" action="" id="addForm"><br>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label layui-bg-gray">菜单名称</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="name" required  lay-verify="required" placeholder="请输入菜单名称" autocomplete="off" class="layui-input">'
		    			+'</div>'
		        	+'</div>'
		       		+'<div class="layui-form-item">'
				        +'<label class="layui-form-label layui-bg-gray">菜单路径</label>'
				        +'<div class="layui-input-inline">'
		        			+'<input type="text" name="path" placeholder="请输入菜单路径" autocomplete="off" class="layui-input">'
		        		+'</div>'
			        +'</div>'
			        +'<div class="layui-form-item">'
		        		+'<label class="layui-form-label layui-bg-gray">权限标识</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="perm" required lay-verify="required" placeholder="请输入权限标识" autocomplete="off" class="layui-input">'
		    			+'</div>'
		        	+'</div>'
		        	+'<div class="layui-form-item" pane>'
		        		+'<label class="layui-form-label layui-bg-gray">父级菜单</label>'
		        		+'<div class="layui-input-block">'
		        			+'<select name="parentId" id="parentId" lay-verify="required">'
						        +'<option value="-1">无</option>'
		        			+'</select>'
		        		+'</div>'
		       		+'</div>'
		       		+'<div class="layui-form-item" pane>'
		        		+'<label class="layui-form-label layui-bg-gray">菜单类型</label>'
		        		+'<div class="layui-input-block">'
		        			+'<select name="type" id="typeId" lay-verify="required">'
						        +'<option value="0">目录</option>'
						        +'<option value="1">菜单</option>'
						        +'<option value="2">操作</option>'
		        			+'</select>'
		        		+'</div>'
		       		+'</div>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label layui-bg-gray">菜单图标</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="icon" placeholder="请输入菜单图标" autocomplete="off" class="layui-input">'
		    			+'</div>'
		        	+'</div>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label layui-bg-gray">排序号</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="sort" lay-verify="number" placeholder="请输入整数排序号" autocomplete="off" class="layui-input">'
		    			+'</div>'
		        	+'</div>'
			        +'<div class="layui-form-item">'
				        +'<div class="layui-input-block">'
							+'<button type="button" class="layui-btn" lay-submit lay-filter="formAdd">提交</button>'
					        +'<button type="reset" class="layui-btn layui-btn-primary">重置</button>'
				        +'</div>'
			        +'</div>'
		        +'</form>';
	}else if(title == '修改'){
		return '<form class="layui-form layui-form-pane" action="" id="updateForm"><br>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label">ID</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="id" readonly lay-verify="required" placeholder="ID" autocomplete="off" class="layui-input" value="' + data.id + '">'
		    			+'</div>'
		        	+'</div>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label">菜单名称</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="name" required  lay-verify="required" placeholder="请输入菜单名称" autocomplete="off" class="layui-input" value="' + data.name + '">'
		    			+'</div>'
		        	+'</div>'
		       		+'<div class="layui-form-item">'
				        +'<label class="layui-form-label">菜单路径</label>'
				        +'<div class="layui-input-inline">'
		        			+'<input type="text" name="path" placeholder="请输入菜单路径" autocomplete="off" class="layui-input" value="' + data.path + '">'
		        		+'</div>'
			        +'</div>'
			        +'<div class="layui-form-item">'
		        		+'<label class="layui-form-label">权限标识</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="perm" required lay-verify="required" placeholder="请输入权限标识" autocomplete="off" class="layui-input" value="' + data.perm + '">'
		    			+'</div>'
		        	+'</div>'
		        	+'<div class="layui-form-item" pane>'
		        		+'<label class="layui-form-label layui-bg-gray">父级菜单</label>'
		        		+'<div class="layui-input-block">'
		        			+'<select name="parentId" id="parentId" lay-verify="required">'
						        +'<option value="-1">无</option>'
		        			+'</select>'
		        		+'</div>'
		       		+'</div>'
		       		+'<div class="layui-form-item" pane>'
		        		+'<label class="layui-form-label layui-bg-gray">菜单类型</label>'
		        		+'<div class="layui-input-block">'
		        			+'<select name="type" id="typeId" lay-verify="required">'
						        +'<option value="0">目录</option>'
						        +'<option value="1">菜单</option>'
						        +'<option value="2">操作</option>'
		        			+'</select>'
		        		+'</div>'
		       		+'</div>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label">菜单图标</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="icon" placeholder="请输入菜单图标" autocomplete="off" class="layui-input" value="' + (data.icon==null ? "" : data.icon) + '">'
		    			+'</div>'
		        	+'</div>'
		        	+'<div class="layui-form-item">'
		        		+'<label class="layui-form-label">排序号</label>'
		        		+'<div class="layui-input-inline">'
		        			+'<input type="text" name="sort" lay-verify="number" placeholder="请输入排序号" autocomplete="off" class="layui-input" value="' + data.sort + '">'
		    			+'</div>'
		        	+'</div>'
			        +'<div class="layui-form-item">'
				        +'<div class="layui-input-block">'
					        +'<button type="button" class="layui-btn" lay-submit lay-filter="formUpdate">提交</button>'
					        +'<button type="reset" class="layui-btn layui-btn-primary">重置</button>'
				        +'</div>'
			        +'</div>'
		        +'</form>';
	}
}

//添加菜单
function addMenu(data){
	layer.load();//加载弹窗
	$.ajax({
        type: "post",
        url : "/admin/sys/menu/save",
        dataType:'json',
        async: false,
        //data: $('#addForm').serialize(),
        data:data,
        success: function(data){	
        	var addSuccess = data.data;
            if(addSuccess){
            	gritterSuccess(addSuccess);
                layer.close(openIndex);//关闭弹窗
            }else{
            	gritterError('添加失败');
            }
            $('#btn-refresh').trigger('click');//刷新列表
        },
        error: function(){
        	gritterError(info.noAuth);
            $('#btn-refresh').trigger('click');//刷新列表
        }
    });
}

//修改菜单
function updateMenu(data){
	layer.load();//加载弹窗
	$.ajax({
        type: "post",
        url : "/admin/sys/menu/update",
        dataType:'json',
        //data: $('#updateForm').serialize(),
        data: data,
        success: function(data){
            var updateSuccess = data.data;
            if(updateSuccess){
            	gritterSuccess(updateSuccess);
                layer.close(openIndex);//关闭弹窗
            }else{
            	gritterError('修改失败');
            }
            $('#btn-refresh').trigger('click');//刷新列表
        },
        error: function(){
        	gritterError(info.noAuth);
        	$('#btn-refresh').trigger('click');//刷新列表
        }
    });
}

//删除菜单
function deleteMenu(id){
	layer.load();//加载弹窗
	var form = layui.form;
	$.ajax({
        type: "post",
        url : "/admin/sys/menu/delete",
        dataType:'json',
        data: {
            "id":id
        },
        success: function(data){
            var delSuccess = data.data;
            if(delSuccess){
            	gritterSuccess(delSuccess);
            }else{
            	gritterError('删除失败');
            }
            $('#btn-refresh').trigger('click');
        },
        error: function(){
        	gritterError(info.noAuth);
        	$('#btn-refresh').trigger('click');//刷新列表
        }
    });
}
			
